<?php

/**
 * news_sort模型
 * @author 
 * @version 1.0
 * @package application
 * @subpackage application/models
 */
class News_class_Model extends MY_Model {

    public static $tree = array();

    public function __construct() {
        parent::__construct();
        $this->_pk = 'id';
        $this->_attributes = array(
            'id' => '',
            'parentid' => '',
            'nodepath' => '',
            'sortname' => '',
            'comment' => '',
            'depth' => '',
            'recycled' => '',
            'created' => '',
            'modified' => '',
            'status' => '',
        );
    }

    /**
     * 获取信息类型分类树
     * @return [array] []
     */
    public static function get_tree($data, $pid = 0, $level = 0) {
        foreach ($data as $key => $value) {
            if ($value['parentid'] == $pid) {
                $row['id'] = $value['id'];
                if ($level != 0) {
                    $row['sortname'] = str_repeat("&nbsp;", $level) . "|--" . $value['sortname'];
                } else {
                    $row['sortname'] = $value['sortname'];
                }
                self::$tree [] = $row;
                unset($data[$key]);
                self::get_tree($data, $value['id'], $level + 1);
            }
        }
        return self::$tree;
    }

    /**
     * 获取下拉列表数组
     * @param  [array] $data [要生成下拉列表数组的原始数组]
     * @return [array]       [下拉列表数组]
     */
    public function get_dropdown_array(&$data) {
        $result = array();
        foreach ($data as $key => $value) {

            $result[$value['id']] = $value['sortname'];
        }

        return $result;
    }

    /**
     * 根据parentid查询nodepath
     * @param  [int] $pid [父id]
     * @return [mixed]      [成功返回nodepath,否则返回false]
     */
    public function get_path_by_parentid($pid) {
        $query = $this->db->select('nodepath')->from($this->table_name())->where('id', $pid);
        $result = $query->get()->row_array();
        if (!result) {
            return false;
        }
        return $result['nodepath'];
    }

    //获取所有父类名称
    public function get_parents_name($nodepath) {

        $ids = explode(',', substr($nodepath, 3, -1));
        $search = array('in' => array('id' => $ids));
        return $this->get_values('id', 'sortname', null, $search);
    }

    /**
     * @access public 获取所有新闻分类
     * @param $arr array 要遍历的数组
     * @param $pid 节点的pid，默认为0，表示从顶级节点开始
     * @param $level int 表示层级 默认为0
     * @param array 排好序的所有后代节点
     */
    public static function _tree($arr, $pid = 0, $level = 0) {
        static $trees = array(); #用于保存重组的结果,注意使用静态变量
        foreach ($arr as $v) {
            if ($v['parent_id'] == $pid) {
                //说明找到了以$pid为父节点的子节点,将其保存
                $trees[] = $v;
                //然后以当前节点为父节点，继续找其后代节点
                self::_tree($arr, $v['id'], $level + 1);
            }
        }
        return $trees;
    }

}
